<?php

namespace Beerus\Modules\BlindBox\Controllers;

use Encore\Admin\Grid;
use Doraemon\tools\ImgUrl;
use Biz\service\brand\Brand;
use Illuminate\Http\Request;
use Encore\Admin\Widgets\Form;
use Biz\service\wiki\WikiBasic;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Illuminate\Support\MessageBag;
use App\Http\Controllers\Controller;
use Biz\model\brand\Brand as mBrand;
use Biz\service\brand\BrandActivity;
use Biz\service\brand\BlindBoxActivity;
use Biz\model\brandActivity\BrandActivityBasic;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\constInterface\SourceRightsInterface;
use Biz\model\brandActivity\BlindBoxActivity as mBlindBoxActivity;
use Biz\model\brandActivity\BlindBoxActivityPrize as mBlindBoxActivityPrize;

class ReservePrizeController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        Admin::style('.span-label{margin-bottom: 5px; cursor: pointer; margin-right: 5px; display: inline-block;}');
        $request_data = $request->all();
        $condition = self::getCondition($request_data);
        $page_size = $request->input("per_page", self::PAGE_SIZE);
        $page = $request->input("page", 1);
        if (!is_null($condition)) {
            $where = $condition;
            $where['LIMIT'] = [
                ($page - 1) * $page_size,
                $page_size
            ];
            $result = self::getReserveList($where);
        } else {
            $result = ['list' => [], 'total' => 0];
        }
        $gridModel = new pGridDataModel($result['list'], $result['total'], [
            'perPage' => $page_size
        ]);
        $gridList = Admin::grid(
            $gridModel,
            function (Grid $grid) use ($gridModel) {
                $grid->paginate($gridModel->getPerPage());
                $grid->disableExport();
                $grid->disableRowSelector();
                // $grid->disableCreateButton();
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        $filter->equal('activity_id', '活动ID');
                        $filter->equal('activity_title', '活动名称');
                    });
                    $filter->column(1 / 2, function (Grid\Filter $filter) {
                        $filter->equal('activity_state', '活动状态')->select(mBlindBoxActivity::$resereveActivityStateDesc);
                        $filter->date('start_time', '上线时间');
                    });
                    $filter->expand();
                });
                $grid->column("id", '活动ID')->width(80);
                $grid->column('title', '活动名称')->width(120);
                $grid->column('prize_type', '奖品类型')->display(function () {
                    $html = '<ul class="list-inline">';
                    $html .= '<li>奖品类型：<b>' . mBlindBoxActivity::$prizeTypeDesc[$this->prize_type] . '</b></li>';
                    switch ($this->prize_type) {
                        case mBlindBoxActivity::PRIZE_TYPE_GOODS:
                            $html .= '<li>WIKI ID：<a href="javascript:void(0);" target="_blank">' . $this->basic_id . '</a></li>';
                            $html .= '<li>奖品名称：' . $this->prize_title . '</li>';
                            break;
                        case mBlindBoxActivity::PRIZE_TYPE_JD_CARD:
                            $html .= '<li>卡号：</li>';
                            foreach ($this->card as $item) {
                                $html .= '<li style="color: #00a65a ">「' . $item . '」</li>';
                            }
                            break;
                        case mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD:
                            $html .= '<li>卡片：</li>';
                            foreach ($this->limit_card as $img) {
                                $html .= '<li style="color: #00a65a "><img width="50" height="50" src="' . $img . '"></li>';
                            }
                            break;
                    }
                    $html .= '</ul>';
                    return $html;
                })->style('min-width:190px');
                $grid->column('prize_img', '奖品图片')->image("", 100, 100);
                $grid->column('screen_capture', '奖品截图')->image("", 100, 100);
                $grid->column('dynamic_img', '中奖动态')->display(function () {
                    $img = BrandActivity::getActivityDynamicImg(BrandActivityBasic::ACTIVITY_TYPE_BLIND_BOX,
                        $this->dynamic_img);
                    $str = '<span style="color: red;font-weight: bolder;font-size: medium">添加动态图</span>';
                    $html = '<ul class="list-inline">';
                    if ($this->dynamic_img) {
                        $html .= '<img src="' . $img . '" style="max-width:100px;max-height:100px" class="img img-thumbnail">';
                        $str = '更改动态图';
                    }
                    $html .= '<li><a href="/admin/blindBox/index/' . $this->id . '/editDynamic">' . $str . '</a></li>';
                    $html .= '</ul>';
                    return $html;
                });
                $grid->column('prize_num', '奖品数量')->width(100);
                $grid->column('prize_price', '单个奖品价值')->width(120);
                $grid->column('prize_total_price', '奖品总价值')->width(100);
                $grid->column('activity_state', '活动状态')->display(function () {
                    return mBlindBoxActivity::$activityStateDesc[$this->activity_state];
                })->width(100);
                $grid->column('prize_stock', '剩余奖品数量')->width(80);
                $grid->column('start_time', '排期')->display(function () {
                    $html = '<div class="span-label">';
                    if ($this->start_time == 0) {
                        $html .= '<span>待排期</span></br>';
                    } else {
                        $html .= '<span>' . date('Ymd', $this->start_time) . '-' . date('Ymd',
                                $this->end_time) . '</span></br>';
                    }
                    $html .= '</div>';
                    return $html;
                })->width(150);
                $grid->actions(function (Grid\Displayers\Actions $actions) {
                    if (in_array($actions->row->activity_state, [
                        mBlindBoxActivity::ACTIVITY_STATE_ONLINE,
                        mBlindBoxActivity::ACTIVITY_STATE_END,
                        mBlindBoxActivity::ACTIVITY_STATE_DEL
                    ])) {
                        //$actions->disableEdit();
                        //$actions->disableDelete();
                    }

                    // 添加中奖信息列表
                    if (in_array($actions->row->activity_state, [mBlindBoxActivity::ACTIVITY_STATE_ONLINE, mBlindBoxActivity::ACTIVITY_STATE_END])) {
                        $actions->prepend('&nbsp;<a class="fa" target="_blank" href="' . url('/admin/blindBox/winnerList?activity_id=' . $actions->row->id) . '">
                            <span class="glyphicon glyphicon-eye-open" aria-hidden="true">中奖信息</span></a>');
                    }
                });
            }
        );
        $content->row($gridList);
        return $content
            ->header('补位奖品列表')
            ->description(' ')
            ->breadcrumb(['text' => '补位奖品列表']);
    }

    public function edit(Request $request, Content $content, $id = 0)
    {
        $info = [];
        $header = '创建补位奖品';
        if ($id) {
            $info = mBlindBoxActivity::getInfoById($id);
            $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($id);
            $activityPrizeList = $activityPrizeList ? $activityPrizeList[$id] : [];
            $card = [];
            $limitCard = [];
            foreach ($activityPrizeList as $row) {
                if (in_array($row['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_JD_CARD])) {
                    $card[] = [
                        'prize_value' => $row['prize_value'],
                        'prize_state_desc' => $row['prize_state'] == (mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) ? '已抽中' : ''
                    ];
                } else {
                    if (in_array($row['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_LIMIT_CARD])) {
                        $limitCard[] = $row['prize_value'];
                    }
                }
            }
            $info['card'] = $card;
            $info['limit_card'] = $limitCard ? implode(',', $limitCard) : '';
            $header = '编辑补位奖品';
        }
        if ($info) {
            switch ($info['prize_type']) {
                case mBlindBoxActivity::PRIZE_TYPE_GOODS:
                    $info['start_time'] = $info ? date('Y-m-d', $info['start_time']) : '';
                    $info['end_time'] = $info ? date('Y-m-d', $info['end_time']) : '';
                    break;
                case mBlindBoxActivity::PRIZE_TYPE_JD_CARD:
                    $info['card_start_time'] = $info ? date('Y-m-d', $info['start_time']) : '';
                    $info['card_end_time'] = $info ? date('Y-m-d', $info['end_time']) : '';
                    $info['card_prize_title'] = $info ? $info['prize_title'] : '';
                    $info['card_prize_price'] = $info ? $info['prize_price'] : 0;
                    $info['card_prize_total_price'] = $info ? $info['prize_total_price'] : 0;
                    if ($info['card']) {
                        foreach ($info['card'] as $row) {
                            $info['card_list'][] = [
                                'card' => $row['prize_value'],
                                'card_state' => $row['prize_state_desc']
                            ];
                        }
                    }
                    break;
                case mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD:
                    $info['limit_start_time'] = $info ? date('Y-m-d', $info['start_time']) : '';
                    $info['limit_end_time'] = $info ? date('Y-m-d', $info['end_time']) : '';
                    $info['limit_prize_title'] = $info ? $info['prize_title'] : '';
                    $info['limit_prize_price'] = $info ? $info['prize_price'] : 0;
                    $info['limit_prize_img'] = $info ? $info['prize_img'] : '';
                    $info['limit_prize_total_price'] = $info ? $info['prize_total_price'] : 0;
                    $info['limit_card'] = $info ? $info['limit_card'] : '';
                    break;
            }
        } else {
            $info['prize_type'] = mBlindBoxActivity::PRIZE_TYPE_GOODS;
        }
        $form = new Form($info);
        if (isset($info['id'])) {
            $form->text('id', '活动ID')->readonly();
        }
        $script = <<<SCRIPT
            var prize_price=$('#prize_price').val();
            var prize_num=$('#prize_num').val();
            var prize_total_price=prize_price*prize_num;
            $('#prize_price').change(function(){
                prize_price=$(this).val();
                prize_num=$('#prize_num').val();
                prize_total_price=prize_price*prize_num;
                $('#prize_total_price').val(prize_total_price);
            });
            $('#prize_num').change(function(){
                console.log($(this).val());
                prize_num=$(this).val();
                prize_price=$('#prize_price').val();
                prize_total_price=prize_price*prize_num;
                $('#prize_total_price').val(prize_total_price);
            });
            $('#card_prize_price').change(function(){
                var card_prize_price=$(this).val();
                console.log(card_prize_price);
                var card_prize_num=0;
                $('.card_list._remove_.fom-removed').each(function(index){
                    if($(this).val()==0){
                        card_prize_num+=1;
                    }
                });
                var card_prize_total_price=card_prize_price*card_prize_num;
                $('#card_prize_total_price').val(card_prize_total_price);
            });
            $("#has-many-card_list").delegate("div.add","click",function(){
                var card_prize_num=1;
                $('.card_list._remove_.fom-removed').each(function(index){
                    if($(this).val()==0){
                        card_prize_num+=1;
                    }
                });
                console.log(card_prize_num);
                var card_prize_price=$('#card_prize_price').val();
                var card_prize_total_price=card_prize_price*card_prize_num;
                $('#card_prize_total_price').val(card_prize_total_price);
            });
            $("#has-many-card_list").delegate("div.remove","click",function(){
                var card_prize_num=0;
                $('.card_list._remove_.fom-removed').each(function(index){
                    if($(this).val()==0){
                        card_prize_num+=1;
                    }
                });
                card_prize_num=card_prize_num?(card_prize_num-1):0;
                console.log(card_prize_num);
                var card_prize_price=$('#card_prize_price').val();
                var card_prize_total_price=card_prize_price*card_prize_num;
                $('#card_prize_total_price').val(card_prize_total_price);
            });
            $('.has-many-card_list-form.fields-group').each(function(){
                var cardstate=$(this).find('input.card_list.card_state').val();
                if(cardstate) {
                    $(this).find('input.form-control.card_list.card').attr('readonly','readonly');
                    $(this).find('i.fa.fa-pencil.fa-fw').after('&nbsp;'+cardstate);
                }
            });
SCRIPT;
        Admin::script($script);
        $radioOption = [
            mBlindBoxActivity::PRIZE_TYPE_GOODS => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_GOODS],
            mBlindBoxActivity::PRIZE_TYPE_JD_CARD => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_JD_CARD],
            mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD],
        ];
        if (isset($info['id'])) {
            if ($info['prize_type'] == mBlindBoxActivity::PRIZE_TYPE_GOODS) {
                $radioOption = [
                    mBlindBoxActivity::PRIZE_TYPE_GOODS => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_GOODS],
                ];
            } else {
                if ($info['prize_type'] == mBlindBoxActivity::PRIZE_TYPE_JD_CARD) {
                    $radioOption = [
                        mBlindBoxActivity::PRIZE_TYPE_JD_CARD => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_JD_CARD],
                    ];
                } else {
                    if ($info['prize_type'] == mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD) {
                        $radioOption = [
                            mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD => mBlindBoxActivity::$prizeTypeDesc[mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD],
                        ];
                    }
                }
            }
        }
        $form->radio('prize_type', '奖品类型')
            ->options($radioOption)->when(mBlindBoxActivity::PRIZE_TYPE_GOODS, function (Form $form) use ($info) {
                $form->text('basic_id', 'wiki ID')->help('必填,注：此处为basic ID 非商品id');
                $form->text('prize_title', '奖品名称')->help('如果不填写，保存后，使用wiki短名');
                $form->dateRange('start_time', 'end_time', '排期')->attribute('autocomplete', 'off')->help('必填');
                $form->decimal('prize_num', '奖品数量')->default(1)->help('必填');
                $form->decimal('prize_price', '单个奖品价值')->default(0)->help('必填');
                $form->decimal('prize_total_price', '奖品总价值')->default(0)->help('必填');
                if ($info) {
                    $form->imgUpload('prize_img', '奖品图片', false, ['isGetUrl' => false])->help('必传');
                }
                $form->imgUpload('screen_capture', '奖品截图', false, ['isGetUrl' => false])->help('必传');
            })->when(mBlindBoxActivity::PRIZE_TYPE_JD_CARD, function (Form $form) use ($info) {
                $form->text('card_prize_title', '奖品名称')->help('必填');
                $form->dateRange('card_start_time', 'card_end_time', '排期')->attribute('autocomplete',
                    'off')->help('必填');
                $form->decimal('card_prize_price', '单个奖品价值')->default(0)->help('必填');
                $form->decimal('card_prize_total_price', '奖品总价值')->default(0)->readonly();
                $form->fieldGroup('card_list', '京东卡密(新增↓)', function ($form) {
                    $form->hidden('group_id', '分组id');
                    $form->text('card', '京东卡密');
                    $form->hidden('card_state', '状态');
                });
                $form->imgUpload('imgs', '商品主图', true, ['isUpload' => true, 'isGetUrl' => true]);
            })->when(mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD, function (Form $form) use ($info) {
                $form->text('limit_prize_title', '奖品名称')->help('必填');
                $form->dateRange('limit_start_time', 'limit_end_time', '排期')->attribute('autocomplete',
                    'off')->help('必填');
                $form->decimal('limit_prize_price', '单个奖品价值')->default(0)->help('必填');
                $form->decimal('limit_prize_total_price', '奖品总价值')->default(0)->readonly();
                $form->imgUpload('limit_prize_img', '奖品图片（单图）', false, ['isGetUrl' => false])->help('必传，单图');
                $form->imgUpload('limit_card', '奖品（多图）', true,
                    ['isUpload' => true, 'isGetUrl' => true])->help('至少一个图片。多个奖品，添加多个图片');
            });
        $form->action('/admin/blindBox/reserve/save');
        $content->row($form);
        if ($info && in_array($info['activity_state'],
                [mBlindBoxActivity::ACTIVITY_STATE_ONLINE, mBlindBoxActivity::ACTIVITY_STATE_END])) {
            $form->disableReset();
            $form->disableSubmit();
        }
        return $content
            ->header($header)
            ->description('')
            ->breadcrumb(
                ['text' => '补位奖品列表', 'url' => url('/admin/blindBox/reserve')],
                ['text' => '编辑补位奖品']
            );
    }

    public function save(Request $request)
    {
        try {
            $adminId = Admin::user()->id;
            $id = $request->input('id', 0);
            $prizeType = $request->input('prize_type', 0);
            if (!$prizeType) {
                throw new \Exception('参数错误');
            }
            $info = $id ? mBlindBoxActivity::getInfoById($id) : [];
            if ($id && $info && $info['brand_id'] > 0) {
                throw new \Exception('非法参数');
            }
            $activityData = [];
            $prizeValue = [];
            switch ($prizeType) {
                case mBlindBoxActivity::PRIZE_TYPE_GOODS:
                    $basicId = $request->input('basic_id', 0);
                    $basicInfos = WikiBasic::getWikiBasicInfoByIds([$basicId]);
                    $basicInfo = ($basicInfos && isset($basicInfos[$basicId])) ? $basicInfos[$basicId] : [];
                    if (!$basicId || !$basicInfo) {
                        throw new \Exception('不存在的wiki');
                    }
                    $prizeTitle = $request->input('prize_title', '');
                    $prizeTitle = $prizeTitle ? $prizeTitle : $basicInfo['title'];
                    $prizeNum = $request->input('prize_num', 0);
                    if ($prizeNum <= 0) {
                        throw new \Exception('必须设置奖品数量');
                    }
                    $prizePrice = $request->input('prize_price', 0);
                    if ($prizePrice <= 0) {
                        throw new \Exception('单个奖品价值必须大于0');
                    }
                    $prizeTotalPrice = bcmul($prizeNum, $prizePrice, 2);
                    $startTime = $request->input('start_time', '');
                    $endTime = $request->input('end_time', '');
                    $screenCapture = $request->input('screen_capture', '');
                    $startTime = $startTime ? strtotime(date('Y-m-d', strtotime($startTime))) : 0;
                    $endTime = $endTime ? strtotime(date('Y-m-d', strtotime($endTime))) + 86399 : 0;
                    if ($startTime >= $endTime) {
                        throw new \Exception('排期开始时间必须小于结束时间');
                    }
                    $screenCapture = $screenCapture ? self::formatImg($screenCapture) : '';
                    if (empty($screenCapture)) {
                        throw new \Exception('必须上传商品截图');
                    }
                    $prizeImg = isset($basicInfo['cover_img']) ? $basicInfo['cover_img'] : '';
                    $activityData = [
                        'id' => $id,
                        'brand_id' => 0,
                        'activity_type' => mBlindBoxActivity::ACTIVITY_TYPE_BLIND_BOX,
                        'title' => '好好住补位奖品-' . mBlindBoxActivity::$prizeTypeDesc[$prizeType],
                        'prize_type' => $prizeType,
                        'basic_id' => $basicId,
                        'prize_title' => $prizeTitle,
                        'prize_num' => $prizeNum,
                        'prize_price' => $prizePrice,
                        'prize_total_price' => $prizeTotalPrice,
                        'prize_img' => $prizeImg,
                        'screen_capture' => $screenCapture,
                        'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
                        'expected_time' => $startTime,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'admin_id' => $adminId
                    ];
                    $prizeValue[] = $basicId;
                    break;
                case mBlindBoxActivity::PRIZE_TYPE_JD_CARD:
                    $prizeTitle = $request->input('card_prize_title', '');
                    if (empty($prizeTitle)) {
                        throw new \Exception('请填写奖品名称');
                    }
                    $prizePrice = $request->input('card_prize_price', 0);
                    if ($prizePrice <= 0) {
                        throw new \Exception('单个奖品价值必须大于0');
                    }
                    $startTime = $request->input('card_start_time', '');
                    $endTime = $request->input('card_end_time', '');
                    $startTime = $startTime ? strtotime(date('Y-m-d', strtotime($startTime))) : 0;
                    $endTime = $endTime ? strtotime(date('Y-m-d', strtotime($endTime))) + 86399 : 0;
                    if ($startTime >= $endTime) {
                        throw new \Exception('排期开始时间必须小于结束时间');
                    }
                    $cardList = $request->input('card_list', []);
                    $card = [];
                    foreach ($cardList as $row) {
                        if (!$row['_remove_'] && $row['card']) {
                            $card[] = $row['card'];
                        }
                    }
                    $card = array_unique($card);
                    $prizeNum = count($card);
                    if ($prizeNum <= 0) {
                        throw new \Exception('请输入京东卡密');
                    }
                    $prizeTotalPrice = bcmul($prizeNum, $prizePrice, 2);
                    $activityData = [
                        'id' => $id,
                        'brand_id' => 0,
                        'activity_type' => mBlindBoxActivity::ACTIVITY_TYPE_BLIND_BOX,
                        'title' => '好好住补位奖品-' . mBlindBoxActivity::$prizeTypeDesc[$prizeType],
                        'prize_type' => $prizeType,
                        'prize_title' => $prizeTitle,
                        'prize_num' => $prizeNum,
                        'prize_stock' => $prizeNum,
                        'prize_price' => $prizePrice,
                        'prize_total_price' => $prizeTotalPrice,
                        'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
                        'expected_time' => $startTime,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'admin_id' => $adminId
                    ];
                    $prizeValue = $card;
                    break;
                case mBlindBoxActivity::PRIZE_TYPE_LIMIT_CARD:
                    $prizeTitle = $request->input('limit_prize_title', '');
                    if (empty($prizeTitle)) {
                        throw new \Exception('请填写奖品名称');
                    }
                    $prizePrice = $request->input('limit_prize_price', 0);
                    if ($prizePrice <= 0) {
                        throw new \Exception('单个奖品价值必须大于0');
                    }
                    $startTime = $request->input('limit_start_time', '');
                    $endTime = $request->input('limit_end_time', '');
                    $startTime = $startTime ? strtotime(date('Y-m-d', strtotime($startTime))) : 0;
                    $endTime = $endTime ? strtotime(date('Y-m-d', strtotime($endTime))) + 86399 : 0;
                    if ($startTime >= $endTime) {
                        throw new \Exception('排期开始时间必须小于结束时间');
                    }
                    $prizeImg = $request->input('limit_prize_img', '');
                    $prizeImg = $prizeImg ? self::formatImg($prizeImg) : '';
                    $limitCard = $request->input('limit_card', '');
                    if (empty($limitCard)) {
                        throw new \Exception('至少设置一个奖品');
                    }
                    $limitCard = explode(',', $limitCard);
                    $limitCard = array_unique($limitCard);
                    $prizeNum = count($limitCard);
                    if ($prizeNum <= 0) {
                        throw new \Exception('至少设置一个奖品');
                    }
                    $prizeTotalPrice = bcmul($prizeNum, $prizePrice, 2);
                    $activityData = [
                        'id' => $id,
                        'brand_id' => 0,
                        'activity_type' => mBlindBoxActivity::ACTIVITY_TYPE_BLIND_BOX,
                        'title' => '好好住补位奖品-' . mBlindBoxActivity::$prizeTypeDesc[$prizeType],
                        'prize_type' => $prizeType,
                        'prize_title' => $prizeTitle,
                        'prize_num' => $prizeNum,
                        'prize_stock' => 2000000000,
                        'prize_price' => $prizePrice,
                        'prize_total_price' => $prizeTotalPrice,
                        'prize_img' => $prizeImg,
                        'activity_state' => mBlindBoxActivity::ACTIVITY_STATE_PASS,
                        'expected_time' => $startTime,
                        'start_time' => $startTime,
                        'end_time' => $endTime,
                        'admin_id' => $adminId
                    ];
                    $prizeValue = $limitCard;
                    break;
                default:
                    break;
            }
            if (!$prizeValue) {
                throw new \Exception('请添加奖品');
            }
            BlindBoxActivity::saveBlindBoxActivity($activityData, $prizeValue, SourceRightsInterface::BLIND_BOX);

            $success = new MessageBag([
                'title' => '保存成功'
            ]);
            return redirect('/admin/blindBox/reserve')->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '修改优惠券信息失败,' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function del(Request $request, $id = 0)
    {
        try {
            $info = mBlindBoxActivity::getByWhere(['id' => $id]);
            if (!$info) {
                throw new \Exception('不存在的活动');
            }
            $now = time();
            if ($info['activity_state'] == mBlindBoxActivity::ACTIVITY_STATE_PASS && $now >= $info['start_time']) {
                throw new \Exception('当前状态不支持删除');
            }
            $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($id);
            if ($activityPrizeList) {
                $activityPrizeList = $activityPrizeList[$id];
                foreach ($activityPrizeList as $row) {
                    if ($row['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) {//如果有奖品被领取了
                        throw new \Exception('奖品：『' . $row['prize_value'] . '』已经被用户领取,不能删除该活动');
                    }
                }
            }
            $result = mBlindBoxActivity::updateData(['activity_state' => mBlindBoxActivity::ACTIVITY_STATE_DEL],
                ['id' => $info['id']]);
            $success = [
                'title' => '活动 ID: ' . $id . ' 删除成功',
                'code' => 1,
            ];
        } catch (\Exception $e) {
            $success = [
                'title' => '删除失败',
                'code' => 0,
                'status' => false,
                'msg' => '错误信息#file:' . $e->getFile() . '#line:' . $e->getLine() . '#msg:' . $e->getMessage(),
            ];
        }
        return response()->json($success);
    }

    private static function getCondition($request)
    {
        $condition['ORDER'] = ['start_time' => 'DESC'];
        if (isset($request['activity_id']) && !empty($request['activity_id'])) {
            $condition['id'] = $request['activity_id'];
            return $condition;
        }
        if (isset($request['start_time']) && strlen(trim($request['start_time'])) > 0) {
            $condition['start_time[>=]'] = strtotime($request['start_time']);
            $condition['start_time[<=]'] = strtotime($request['start_time']) + 86399;
            return $condition;
        }
        if (isset($request['activity_title']) && strlen(trim($request['activity_title'])) > 0) {
            $condition['title[~]'] = trim($request['activity_title']);
        }
        if (isset($request['activity_state']) && strlen($request['activity_state']) > 0 && in_array($request['activity_state'],
                array_keys(mBlindBoxActivity::$activityStateDesc))) {
            $now = time();
            switch ($request['activity_state']) {
                case mBlindBoxActivity::ACTIVITY_STATE_PASS:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['OR'] = [
                        'start_time[>]' => $now,
                        'start_time' => 0,
                    ];
                case mBlindBoxActivity::ACTIVITY_STATE_ONLINE:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['start_time[<=]'] = $now;
                    $condition['end_time[>=]'] = $now;
                    break;
                case mBlindBoxActivity::ACTIVITY_STATE_END:
                    $condition['activity_state'] = mBlindBoxActivity::ACTIVITY_STATE_PASS;
                    $condition['end_time[<]'] = $now;
                    $condition['start_time[>]'] = 0;
                    $condition['end_time[>]'] = 0;
                    break;
                default:
                    $condition['activity_state'] = $request['activity_state'];
                    break;
            }
        }
        if (isset($request['brand_id']) && !empty($request['brand_id'])) {
            $condition['brand_id'] = $request['brand_id'];
        } else {
            if (isset($request['brand_name']) && strlen(trim($request['brand_name'])) > 0) {
                $brandIds = mBrand::getBrandByFilter(['brand_name' => $request['brand_name']], 'id');
                if ($brandIds) {
                    $condition['brand_id'] = $brandIds;
                } else {
                    $condition = null;
                }
            }
        }
        return $condition;
    }


    private static function getReserveList($where)
    {
        $where['brand_id'] = 0;
        $list = mBlindBoxActivity::getBlindBoxList($where);
        $activityIds = array_column($list, 'id');
        $activityPrizeList = mBlindBoxActivityPrize::getActivityPrizeList($activityIds);
        $brandIds = array_column($list, 'brand_id');
        $brandIds = array_unique($brandIds);
        $brandInfos = Brand::getBrandInfoByIds4Goods($brandIds);
        $result = [];
        foreach ($list as $id => $row) {
            $prizeList = isset($activityPrizeList[$id]) ? $activityPrizeList[$id] : [];
            $receivedCount = 0;
            $card = [];
            $limitCard = [];
            foreach ($prizeList as $prizeInfo) {
                if (in_array($prizeInfo['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_JD_CARD])) {
                    $card[] = $prizeInfo['prize_value'];
                } else {
                    if (in_array($prizeInfo['prize_type'], [mBlindBoxActivityPrize::PRIZE_TYPE_LIMIT_CARD])) {
                        $img = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $prizeInfo['prize_value'], ImgUrl::IMAGE_SIZE_OP_ORI);
                        $limitCard[] = $img;
                    }
                }
                if ($prizeInfo['prize_state'] == mBlindBoxActivityPrize::PRIZE_STATE_RECEIVED) {
                    $receivedCount++;
                }
            }
            $row['brand_name'] = isset($brandInfos[$row['brand_id']]) ? $brandInfos[$row['brand_id']]['name'] : '';
            $row['prize_stock'] = $row['prize_stock'];//奖品剩余数量
            $row['card'] = $card;
            $row['limit_card'] = $limitCard;
            $result[] = $row;
        }
        unset($where['LIMIT']);
        unset($where['ORDER']);
        $total = mBlindBoxActivity::getBlindBoxCount($where);
        return ['list' => $result, 'total' => $total];
    }

    private static function formatImg($pic_id)
    {
        $pattern = '/(http|https):\/\/([\w.]+\/?)\S*/';
        if (preg_match($pattern, $pic_id) || strpos($pic_id, '//') === 0) {
            $url = $pic_id;
        } else {
            $url = $pic_id ? ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $pic_id, ImgUrl::IMAGE_SIZE_OP_ORI) : '';
        }
        return $url;
    }

}
